<template>
  <div>
    <div class="card" style="padding: 15px">
      您好，{{ user?.name }}！欢迎使用本系统
    </div>

    <div style="display: flex; margin: 10px 0">
      <div style="width: 50%" class="card">
        <div style="margin-bottom: 30px; font-size: 20px; font-weight: bold">
          公告列表
        </div>
        <div>
          <el-timeline reverse slot="reference">
            <el-timeline-item
              v-for="item in notices"
              :key="item.id"
              :timestamp="item.time"
            >
              <el-popover
                placement="right"
                width="200"
                trigger="hover"
                :content="item.content"
              >
                <span slot="reference">{{ item.title }}</span>
              </el-popover>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <div class="flex-1 m-l-10">
        <el-card class="box-card">
          <div class="card-biaoti">
            <div class="title">
              <i class="el-icon-trophy"></i>
              总营业额：
            </div>
            <h1>￥ {{ totalAmount }} 元</h1>
          </div>
        </el-card>

        <el-card class="box-card m-t-10">
          <div class="card-biaoti">
            <div class="title">
              <i class="el-icon-trophy"></i>
              总订单：
            </div>
            <h1>{{ totalleng }}</h1>
          </div>
        </el-card>
      </div>
    </div>

    <div style="margin: 10px 0; display: flex; grid-gap: 10px">
      <div style="flex: 1" class="card">
        <div id="bar" style="height: 400px"></div>
      </div>
      <div style="flex: 1" class="card">
        <div id="pie" style="height: 400px"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from "dayjs";

const barOption = {
  title: {
    text: "各类活动报名数量统计",
    left: "center",
  },
  tooltip: {
    trigger: "axis",
  },
  legend: {
    left: "left",
  },
  xAxis: {
    type: "category",
    data: [],
    axisLabel: {
      show: true, // 是否显示刻度标签，默认显示
      interval: 0, // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
      rotate: -60, // 刻度标签旋转的角度，在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠；旋转的角度从-90度到90度
      inside: false, // 刻度标签是否朝内，默认朝外
      margin: 6, // 刻度标签与轴线之间的距离
    },
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      data: [],
      type: "bar",
      itemStyle: {
        normal: {
          color: function (params) {
            // 根据索引返回对应的颜色
            let colorList = [
              "#ffaa2e",
              "#32C5E9",
              "#fa4c4c",
              "#08b448",
              "#FFDB5C",
              "#ff9f7f",
              "#fb7293",
              "#E062AE",
              "#E690D1",
              "#e7bcf3",
            ];
            return colorList[params.dataIndex];
          },
        },
      },
    },
  ],
};

const pieOption = {
  title: {
    text: "各类服务预约统计",
    subtext: "比例图",
    left: "center",
  },
  tooltip: {
    trigger: "item",
  },
  legend: {
    orient: "vertical",
    left: "left",
  },
  series: [
    {
      type: "pie",
      center: ["50%", "60%"],
      radius: "50%",
      data: [],
      label: {
        show: true,
        formatter(param) {
          return param.name + " (" + param.percent + "%)";
        },
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)",
        },
      },
    },
  ],
};

const jinrujiner = () => {
  return {
    tooltip: {
      trigger: "item",
    },

    legend: {
      top: "5%",
      left: "center",
    },
    series: [
      {
        name: "Access From",
        type: "pie",
        avoidLabelOverlap: false,
        radius: ["40%", "70%"],
        label: {
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [],
      },
    ],
  };
};

function categorizeOrdersByDay(orders, days = 7) {
  const now = dayjs(); // 当前时间
  const categorizedOrders = {};

  for (const order of orders) {
    const createTime = dayjs(order.fuwudate); // 订单创建时间
    const differenceInDays = now.diff(createTime, "day"); // 计算与当前时间的差值（天）

    if (differenceInDays < days) {
      const dateKey = createTime.format("DD"); // 按创建日期归类
      if (!categorizedOrders[dateKey]) {
        categorizedOrders[dateKey] = 0;
      }
      categorizedOrders[dateKey] += 1;
    }
  }

  return categorizedOrders;
}

export default {
  name: "Home",
  data() {
    return {
      user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
      notices: [],
      totalAmount: 0,
      totalleng: 0,
    };
  },
  created() {
    this.$request.get("/notice/selectAll").then((res) => {
      this.notices = res.data || [];
    });
  },
  mounted() {
    let barDom = document.getElementById("bar");
    let barChart = echarts.init(barDom);

    let pieDom = document.getElementById("pie");
    let pieChart = echarts.init(pieDom);
    const pieOption = jinrujiner();

    const pieOption2 = jinrujiner();
    this.$request.get("/order/getlist").then((res) => {
      this.totalleng = res.data?.length;
      this.totalAmount = res.data.reduce((a, b) => a + Number(b.jiner), 0);

      let jindatas = res.data.filter((fv) =>
        dayjs(fv.fuwudate).isSame(dayjs(), "day")
      );
      let jinerAll = jindatas.reduce((a, b) => a + b.jiner, 0);
      pieOption.series[0].data = [
        { value: jinerAll, name: "今日收入" },
        { value: jindatas.length, name: "今日订单数" },
      ];
      pieChart.setOption(pieOption);

      let jinyuedatas = res.data.filter((fv) =>
        dayjs(fv.fuwudate).isSame(dayjs(), "month")
      );
      let jinyueAll = jindatas.reduce((a, b) => a + b.jiner, 0);
      pieOption2.series[0].data = [
        { value: jinyueAll, name: "今月收入" },
        { value: jinyuedatas.length, name: "今月订单数" },
      ];

      const datas = categorizeOrdersByDay(res.data);
      let xAxis = Object.keys(datas)
        .sort((a, b) => a - b)
        .map((v) => `${v}号`);

      const series = {
        name: "订单数",
        type: "bar",
        itemStyle: {
          color: "rgb(128, 255, 179)",
        },
        data: Object.values(datas),
      };

      barChart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        title: {
          text: "近7天订单数",
        },
        legend: {
          data: xAxis,
        },
        xAxis: [
          {
            type: "category",
            data: xAxis,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            max: Math.max(...series.data) + 10,
            type: "value",
          },
        ],
        series: series,
      });
    });

    /* this.$request.get("/activitySign/selectAll").then((res) => {
      // let xAxisdata = res.data.filter(v=> v.)
      barOption.xAxis.data = res.data?.map((v) => v.name);
      barOption.series[0].data = res.data?.map((v) => v.value);
      barChart.setOption(barOption);
    });

    let pieDom = document.getElementById("pie");
    let pieChart = echarts.init(pieDom);

    this.$request.get("/reserve/selectCount").then((res) => {
      pieOption.series[0].data = res.data || [];
      pieChart.setOption(pieOption);
    }); */
  },
};
</script>
<style lang="scss" scoped>
.card-biaoti {
  display: flex;
  flex-direction: column;
  align-items: center;

  h1 {
    font-size: 40px;
    margin-top: 20px;
  }

  .title {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 700;

    i {
      margin-right: 10px;
    }
  }
}
</style>
